package org.manager.generic.web;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import net.sf.json.JSON;
import net.sf.json.JSONSerializer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.view.json.JsonStringWriter;
import org.springframework.web.servlet.view.json.JsonWriterConfiguratorTemplateRegistry;

public class RuleJsonlibJsonStringWriter implements JsonStringWriter {

	protected final Log logger = LogFactory.getLog(getClass());

	@SuppressWarnings("unchecked")
	public void convertAndWrite(Map model, JsonWriterConfiguratorTemplateRegistry configuratorTemplateRegistry, Writer writer, BindingResult br) throws IOException{
		
		RuleJsonConfig jsonConfig = (RuleJsonConfig)model.get(JsonViewUtil.JSON_CONF);
		if(jsonConfig == null){
			jsonConfig = JsonViewUtil.createJsonConfig(null);
		}
		
		String outputJson = "";
		
		if(jsonConfig.isDataAsJsonString()){
			outputJson = (String)model.get(JsonViewUtil.DATA_NAME);
		}else{
			JSON json = JSONSerializer.toJSON(model, jsonConfig );
			outputJson = json.toString();
		}
		 
		
		if(logger.isDebugEnabled()){
			logger.debug(outputJson);
		}
		writer.write(outputJson);
		writer.flush();
	}
	
	
}
